package com.dcbeida.fragment;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dcbeida.MyApplication;
import com.dcbeida.R;
import com.dcbeida.activity.CaptureActivity;
import com.dcbeida.activity.HomeActivity;
import com.dcbeida.activity.login.LoginWithCodeActivity;
import com.dcbeida.activity.msg.MsgActivity;
import com.dcbeida.activity.sales.StoresalesActivity;
import com.dcbeida.activity.store.StoreActivity;
import com.dcbeida.activity.zyff.GiveDrugTypeChooseActivity;
import com.dcbeida.adapter.GalleryAdapter;
import com.dcbeida.adapter.HomePageAdapter;
import com.dcbeida.adapter.HomePageFragmentAdapter;
import com.dcbeida.bean.Drug;
import com.dcbeida.bean.DrugListBean;
import com.dcbeida.bean.LengthObj;
import com.dcbeida.bean.MsgBean;
import com.dcbeida.bean.ShopSummary;
import com.dcbeida.bean.ShopSummaryCurrent;
import com.dcbeida.fragment.homeFragment.HomeContract;
import com.dcbeida.fragment.homeFragment.HomePresenter;
import com.dcbeida.listern.DialogListener;
import com.dcbeida.listern.OnKeyListener;
import com.dcbeida.mine.MyClientActivity;
import com.dcbeida.utils.DialogUtils;
import com.dcbeida.utils.ScalePageTransformer;
import com.dcbeida.utils.SharedPreferencesUtils;
import com.dcbeida.utils.Utils;
import com.umeng.message.PushAgent;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 首页
 * Created by swt on 2016/11/17.
 */

public class Home2Fragment extends BaseFragment implements HomeContract.View {

    @Bind(R.id.tv_shop_name)
    TextView tv_shop_name;

    @Bind(R.id.btnRight)
    ImageView btnRight;
    @Bind(R.id.btnRed)
    ImageView btnRed;

    @Bind(R.id.input_search)
    EditText inputSearch;
    @Bind(R.id.ll_search)
    LinearLayout llSearch;

    @Bind(R.id.lin_mdxs)
    LinearLayout lin_mdxs;

    @Bind(R.id.lin_yprk)
    LinearLayout lin_yprk;

    @Bind(R.id.lin_ypcx)
    LinearLayout lin_ypcx;
    @Bind(R.id.lin_zyff)
    LinearLayout lin_zyff;


    @Bind(R.id.vp_page)
    ViewPager vp_page;

    @Bind(R.id.lin_point)
    LinearLayout lin_point;


    @Bind(R.id.tv_news)
    TextView tvNews;
    @Bind(R.id.tv_news_time)
    TextView tvNewsTime;
    @Bind(R.id.ll_news)
    LinearLayout llNews;

    private HomePresenter mPresent;

    private PushAgent mPushAgent;
    private MyReceiver myReceiver;
    private MsgReceiver newMsg;
    HomePageFragmentAdapter homePageFragmentAdapter;

    private int dialogCount =0;


    @Override
    public View initViews() {
        View view = View.inflate(mActivity, R.layout.home_fragment2, null);
        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void initData() {
        inputSearch.setFocusable(false);
        tv_shop_name.setText(R.string.app_name);
        inputSearch.setFocusable(false);
        inputSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {


            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(inputSearch.getText().toString().trim())) {
                    llSearch.setGravity(Gravity.LEFT | Gravity.CENTER);
                } else {
                    llSearch.setGravity(Gravity.CENTER);
                }
                inputSearch.setGravity(Gravity.LEFT | Gravity.CENTER);
                Drawable img_off = getResources().getDrawable(R.drawable.sousuo);
                //调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
                img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
                inputSearch.setCompoundDrawables(img_off, null, null, null); //设置左图标
            }
        });

        Utils.setOnKeySearch(inputSearch, new OnKeyListener() {
            @Override
            public void search() {
                inputSearch.setFocusable(false);

            }
        });


        mPresent = new HomePresenter(this, mActivity);
        if (MyApplication.bindDevicetoken != null)
            mPresent.bindDevicetoken(MyApplication.bindDevicetoken);


        mPresent.getNews("0", "1");

        myReceiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(MyApplication.UPDATE_STATUS_ACTION);
        getActivity().registerReceiver(myReceiver, filter);

        newMsg = new MsgReceiver();
        filter = new IntentFilter();
        filter.addAction(MyApplication.NEW_MSG);
        getActivity().registerReceiver(newMsg, filter);


        mPushAgent = PushAgent.getInstance(getActivity());
        mPushAgent.onAppStart();


    }

    @Override
    public void onResume() {
        super.onResume();
        mPresent.getdruglist();
        mPresent.checklogintoken();
        mPresent.getUnReadNews();
    }

    SharedPreferencesUtils sp;

    private void refreshMsg() {
        if (sp == null)
            sp = SharedPreferencesUtils.getInstance(getActivity());
//        if (sp.getIsHidden())//消息已读
//            btnRed.setVisibility(View.GONE);
//        else
//            btnRed.setVisibility(View.VISIBLE);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {   // 不在最前端显示 相当于调用了onPause();
        } else {  // 在最前端显示 相当于调用了onResume();
            //刷新数据
            Log.d("onHiddenChanged", "onHiddenChanged: ");
            refreshMsg();

        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        getActivity().unregisterReceiver(myReceiver);
        getActivity().unregisterReceiver(newMsg);
    }

    @Override
    public void setPresenter(HomeContract.Present presenter) {

    }

    @Override
    public void showTip(String msg) {
        Utils.showTip(getActivity(), msg);
    }

    @Override
    public void showShopSummaryCurrent(ShopSummaryCurrent data) {


    }

    @Override
    public void showShopSummary(ShopSummary shopSummary) {

    }

    @Override
    public void showNews(ArrayList<MsgBean> list) {
        if (null != list && 0 < list.size()) {
            llNews.setVisibility(View.VISIBLE);
            MsgBean bean = list.get(0);
            tvNews.setText(bean.getTitle());
            tvNewsTime.setText(bean.getCreatetime());
        } else {
            llNews.setVisibility(View.GONE);
        }
    }

    @Override
    public void showDrugIds(DrugListBean data) {
        MyApplication.getInstance().setmDrugBean(data);

        vp_page.setOffscreenPageLimit(3);
        vp_page.setPageTransformer(true, new ScalePageTransformer(true));


        //---------测试数据
//        List<Drug> list = new ArrayList<>();
//        list.addAll(data.getList());
//        Drug drug = new Drug();
//        drug.setDrugid(data.getList().get(0).getDrugid());
//        list.add(drug);
        //--------end------
        //homePageFragmentAdapter.addAll(data.getList());
        //homePageFragmentAdapter.addAll(list);
        List<Drug> tempList = new ArrayList<>();
        Drug drug = new Drug();
        drug.setDrugid(0);
        drug.setDrugname("销售概况");
        tempList.add(drug);
        tempList.addAll(data.getList());

        homePageFragmentAdapter = new HomePageFragmentAdapter(getChildFragmentManager(), tempList);
        vp_page.setAdapter(homePageFragmentAdapter);

        lin_point.removeAllViews();
        if (homePageFragmentAdapter.getCount() < 2) {
            lin_point.setVisibility(View.INVISIBLE);
        }
        for (int i = 0; i < homePageFragmentAdapter.getCount(); i++) {
            View view = LayoutInflater.from(mActivity).inflate(R.layout.point_item, lin_point, true);
            if (i == 0)
                view.setSelected(true);

        }

        vp_page.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < lin_point.getChildCount(); i++) {
                    lin_point.getChildAt(i).setSelected(false);
                }
                lin_point.getChildAt(position).setSelected(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }

    @Override
    public void logout() {
        ((HomeActivity) getActivity()).showActivity(LoginWithCodeActivity.class,null);
        getActivity().finish();
    }

    @Override
    public void logoutTips() {
        DialogUtils.showConfirm(getActivity(), "登陆信息已过期，请重新登陆。", new DialogListener() {
            @Override
            public void onCancl(Dialog dialog) {

            }

            @Override
            public void onConfirm(Dialog dialog) {
                logout();
            }
        },R.string.confim);
    }

    @Override
    public void handleMsg(int count) {
        if(count>0){
            btnRed.setVisibility(View.VISIBLE);
            showUnReadNewDiloag(count);
        }else {
            btnRed.setVisibility(View.GONE);
        }
    }


    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (MyApplication.bindDevicetoken != null)
                mPresent.bindDevicetoken(MyApplication.bindDevicetoken);
        }
    }

    class MsgReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            refreshMsg();
        }
    }

    @OnClick({R.id.input_search, R.id.ll_search, R.id.btnRight, R.id.lin_mdxs,
            R.id.lin_yprk, R.id.lin_ypcx, R.id.ll_news, R.id.lin_zyff})
    public void onClick(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.input_search:
            case R.id.ll_search:
//                hideKeyBoard();
                bundle.putString("search", "search");
                ((HomeActivity) getActivity()).showActivity(MyClientActivity.class, bundle);
                break;
            case R.id.btnRight:
                ((HomeActivity) getActivity()).showActivity(MsgActivity.class, null);
                break;
            case R.id.ll_news:
                ((HomeActivity) getActivity()).showActivity(MsgActivity.class, null);
                break;
            case R.id.lin_mdxs:
                ((HomeActivity) mActivity).showActivity(StoresalesActivity.class, null);
                break;
            case R.id.lin_yprk:
                ((HomeActivity) mActivity).showActivity(StoreActivity.class, null);
                break;
            case R.id.lin_ypcx:
                ((HomeActivity) mActivity).showActivity(CaptureActivity.class, null);
                break;
            case R.id.lin_zyff:
                ((HomeActivity) mActivity).showActivity(GiveDrugTypeChooseActivity.class, null);
                break;
        }
    }

    // 隐藏键盘
    private void hideKeyBoard() {
        setFocus(inputSearch, true);
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(inputSearch, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public void setFocus(EditText editText, boolean focusable) {
        editText.setFocusable(focusable);
        editText.setFocusableInTouchMode(focusable);
        editText.requestFocus();
        editText.requestFocusFromTouch();
    }

    public void reFresh() {
        mPresent.getdruglist();
        mPresent.getNews("0", "1");
    }


    public void showUnReadNewDiloag(int count){
        if(dialogCount >0){
            return;
        }
        dialogCount++;
        DialogUtils.showConfirmAndCancel(getActivity(), "您有"+count+"条消息未读,请点击确认进行阅读", new DialogListener() {
            @Override
            public void onCancl(Dialog dialog) {
                dialog.cancel();
            }

            @Override
            public void onConfirm(Dialog dialog) {
                dialog.cancel();
                ((HomeActivity) getActivity()).showActivity(MsgActivity.class, null);
            }
        },R.string.cancel,R.string.confim);
    }
}
